package com.eunion.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.net.HttpHeaders;

/**
 * Http与Servlet工具类. 对请求头的处理，以及发送http请求
 */
@SuppressWarnings({"rawtypes"})
public class ServletUtil {

    public static final String[] MOBILE_AGENTS = {"iphone", "android", "phone", "mobile", "wap", "netfront", "java", "opera mobi", "opera mini", "ucweb", "windows ce", "symbian", "series", "webos",
        "sony", "blackberry", "dopod", "nokia", "samsung", "palmsource", "xda", "pieplus", "meizu", "midp", "cldc", "motorola", "foma", "docomo", "up.browser", "up.link", "blazer", "helio", "hosin",
        "huawei", "novarra", "coolpad", "webos", "techfaith", "palmsource", "alcatel", "amoi", "ktouch", "nexian", "ericsson", "philips", "sagem", "wellcom", "bunjalloo", "maui", "smartphone",
        "iemobile", "spice", "bird", "zte-", "longcos", "pantech", "gionee", "portalmmm", "jig browser", "hiptop", "benq", "haier", "^lct", "320x320", "240x320", "176x220", "w3c ", "acs-", "alav",
        "alca", "amoi", "audi", "avan", "benq", "bird", "blac", "blaz", "brew", "cell", "cldc", "cmd-", "dang", "doco", "eric", "hipt", "inno", "ipaq", "java", "jigs", "kddi", "keji", "leno", "lg-c",
        "lg-d", "lg-g", "lge-", "maui", "maxo", "midp", "mits", "mmef", "mobi", "mot-", "moto", "mwbp", "nec-", "newt", "noki", "oper", "palm", "pana", "pant", "phil", "play", "port", "prox", "qwap",
        "sage", "sams", "sany", "sch-", "sec-", "send", "seri", "sgh-", "shar", "sie-", "siem", "smal", "smar", "sony", "sph-", "symb", "t-mo", "teli", "tim-", "tosh", "tsm-", "upg1", "upsi", "vk-v",
        "voda", "wap-", "wapa", "wapi", "wapp", "wapr", "webc", "winw", "winw", "xda", "xda-", "Googlebot-Mobile"};

    // -- 常用数值定义 --//
    // public static final long ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;

    public static final String DOWNLOAD_MIME = "application/octet-stream;charset=UTF-8";

    public static final String DISPOSITION = "Content-Disposition";

    public static final String CONTENT_LENGTH = "Content-Length";

    public static final String ATTACH_FILE = "attachment;filename=";

    public static final String INLINE_FILE = "inline;filename=";

    private static Logger LOGGER = LoggerFactory.getLogger(ServletUtil.class);

    public static TrustManager MYX_509_TRUST_MANAGER = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {}

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {}

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    /**
     * 设置客户端缓存过期时间 的Header.
     */
    public static void setExpiresHeader(HttpServletResponse response, long expiresSeconds) {
        // Http 1.0 header, set a fix expires date.
        response.setDateHeader(HttpHeaders.EXPIRES, System.currentTimeMillis() + expiresSeconds * 1000);
        // Http 1.1 header, set a time after now.
        response.setHeader(HttpHeaders.CACHE_CONTROL, "private, max-age=" + expiresSeconds);
    }

    /**
     * 设置禁止客户端缓存的Header.
     */
    public static void setNoCacheHeader(HttpServletResponse response) {
        // Http 1.0 header
        response.setDateHeader(HttpHeaders.EXPIRES, 1L);
        response.addHeader(HttpHeaders.PRAGMA, "no-cache");
        // Http 1.1 header
        response.setHeader(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, max-age=0");
    }

    /**
     * 设置LastModified Header.
     */
    public static void setLastModifiedHeader(HttpServletResponse response, long lastModifiedDate) {
        response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedDate);
    }

    /**
     * 设置Etag Header.
     */
    public static void setEtag(HttpServletResponse response, String etag) {
        response.setHeader(HttpHeaders.ETAG, etag);
    }

    /**
     * 根据浏览器If-Modified-Since Header, 计算文件是否已被修改. 如果无修改, checkIfModify返回false ,设置304 not modify status.
     * @param lastModified 内容的最后修改时间.
     */
    public static boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, long lastModified) {
        long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
        if ((ifModifiedSince != -1) && (lastModified < ifModifiedSince + 1000)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return false;
        }
        return true;
    }

    /**
     * 根据浏览器 If-None-Match Header, 计算Etag是否已无效. 如果Etag有效, checkIfNoneMatch返回false, 设置304 not modify status.
     * @param etag 内容的ETag.
     */
    public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response, String etag) {
        String headerValue = request.getHeader(HttpHeaders.IF_NONE_MATCH);
        if (headerValue != null) {
            boolean conditionSatisfied = false;
            if (!"*".equals(headerValue)) {
                StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

                while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                    String currentToken = commaTokenizer.nextToken();
                    if (currentToken.trim().equals(etag)) {
                        conditionSatisfied = true;
                    }
                }
            } else {
                conditionSatisfied = true;
            }

            if (conditionSatisfied) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                response.setHeader(HttpHeaders.ETAG, etag);
                return false;
            }
        }
        return true;
    }

    /**
     * 设置让浏览器弹出下载对话框的Header.
     * @param fileName 下载后的文件名.
     */
    public static void setFileDownloadHeader(HttpServletResponse response, String fileName) {
        try {
            // 中文文件名支持
            String encodedfileName = new String(fileName.getBytes(), "ISO8859-1");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedfileName + "\"");
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    /**
     * 取得带相同前缀的Request Parameters, copy from spring WebUtils. 返回的结果的Parameter名已去除前缀.
     */
    public static Map<String, Object> getParametersStartingWith(ServletRequest request, String prefix) {
        Validate.notNull(request, "Request must not be null");
        Enumeration paramNames = request.getParameterNames();
        Map<String, Object> params = new TreeMap<String, Object>();
        if (prefix == null) {
            prefix = "";
        }
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = ((String) paramNames.nextElement());
            if ("".equals(prefix) || paramName.startsWith(prefix)) {
                String unprefixed = paramName.substring(prefix.length());
                String[] values = request.getParameterValues(paramName);
                if (values == null || values.length == 0) {
                    // Do nothing, no values found at all.
                } else if (values.length > 1) {
                    params.put(unprefixed.trim(), values);
                } else {
                    params.put(unprefixed.trim(), values[0]);
                }
            }
        }
        return params;
    }

    /**
     * 取得带相同前缀的Request Parameters, copy from spring WebUtils. 返回的结果的Parameter名已去除前缀.
     */
    public static Map<String, Object> getAttrbuteStartingWith(ServletRequest request, String prefix) {
        Validate.notNull(request, "Request must not be null");
        Enumeration paramNames = request.getAttributeNames();
        Map<String, Object> params = new TreeMap<String, Object>();
        if (prefix == null) {
            prefix = "";
        }
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = ((String) paramNames.nextElement());
            if ("".equals(prefix) || paramName.startsWith(prefix)) {
                String unprefixed = paramName.substring(prefix.length());
                String values = (String) request.getAttribute(paramName);
                if (values == null) {
                    // Do nothing, no values found at all.
                } else {
                    params.put(unprefixed.trim(), values);
                }
            }
        }
        return params;
    }

    /**
     * 组合Parameters生成Query String的Parameter部分, 并在paramter name上加上prefix.
     * @see #getParametersStartingWith
     */
    public static String encodeParameterStringWithPrefix(Map<String, Object> params, String prefix) {
        if (params == null || params.size() == 0) {
            return "";
        }

        if (prefix == null) {
            prefix = "";
        }

        StringBuilder queryStringBuilder = new StringBuilder();
        Iterator<Entry<String, Object>> it = params.entrySet().iterator();
        while (it.hasNext()) {
            Entry<String, Object> entry = it.next();
            queryStringBuilder.append(prefix).append(entry.getKey()).append('=').append(entry.getValue());
            if (it.hasNext()) {
                queryStringBuilder.append('&');
            }
        }
        return queryStringBuilder.toString();
    }

    /**
     * 客户端对Http Basic验证的 Header进行编码.
     */
    public static String encodeHttpBasic(String userName, String password) {
        String encode = userName + ":" + password;
        return "Basic " + Base64.encodeBase64String(encode.getBytes());
    }

    /**
     * 发送http Post请求
     * @param url
     * @param data
     * @return
     */
    public static String sendHttpsPOST(String url, String data) {
        String result = null;
        try {
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] {MYX_509_TRUST_MANAGER}, null);

            // 打开连接
            // 要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
            URL requestUrl = new URL(url);
            HttpsURLConnection httpsConn = (HttpsURLConnection) requestUrl.openConnection();

            // 设置套接工厂
            httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());

            // 加入数据
            httpsConn.setRequestMethod("POST");
            httpsConn.setDoOutput(true);
            OutputStream out = httpsConn.getOutputStream();

            if (data != null) out.write(data.getBytes("UTF-8"));
            out.flush();
            out.close();

            // 获取输入流
            BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
            int code = httpsConn.getResponseCode();
            if (HttpsURLConnection.HTTP_OK == code) {
                String temp = in.readLine();
                /* 连接成一个字符串 */
                while (temp != null) {
                    if (result != null)
                        result += temp;
                    else
                        result = temp;
                    temp = in.readLine();
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 返回数据为utf-8格式
     * @param url
     * @param data
     * @return
     */
    public static String sendHttpsPOST_UTF8(String url, String data) {
        String result = null;
        try {
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] {MYX_509_TRUST_MANAGER}, null);

            // 打开连接
            // 要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
            URL requestUrl = new URL(url);
            HttpsURLConnection httpsConn = (HttpsURLConnection) requestUrl.openConnection();

            // 设置套接工厂
            httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());

            // 加入数据
            httpsConn.setRequestMethod("POST");
            httpsConn.setDoOutput(true);
            OutputStream out = httpsConn.getOutputStream();

            if (data != null) out.write(data.getBytes("UTF-8"));
            out.flush();
            out.close();

            // 获取输入流
            BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream(), "UTF-8"));
            int code = httpsConn.getResponseCode();
            if (HttpsURLConnection.HTTP_OK == code) {
                String temp = in.readLine();
                /* 连接成一个字符串 */
                while (temp != null) {
                    if (result != null)
                        result += temp;
                    else
                        result = temp;
                    temp = in.readLine();
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return result;
    }

    /***
     * 发送GET请求
     * @param url
     * @return
     */
    public static String sendHttpsGET(String url) {
        String result = null;
        try {
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] {MYX_509_TRUST_MANAGER}, null);

            // 打开连接
            // 要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
            URL requestUrl = new URL(url);
            HttpsURLConnection httpsConn = (HttpsURLConnection) requestUrl.openConnection();

            // 设置套接工厂
            httpsConn.setSSLSocketFactory(sslcontext.getSocketFactory());

            // 加入数据
            httpsConn.setRequestMethod("GET");
            // httpsConn.setDoOutput(true);

            // 获取输入流
            BufferedReader in = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
            int code = httpsConn.getResponseCode();
            if (HttpsURLConnection.HTTP_OK == code) {
                String temp = in.readLine();
                /* 连接成一个字符串 */
                while (temp != null) {
                    if (result != null)
                        result += temp;
                    else
                        result = temp;
                    temp = in.readLine();
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return result;
    }

    /**
     * 发送POST请求
     * @param url
     * @param para 参数
     * @return
     * @throws Exception
     */
    public static String sendHttpPost(String url, Map<String, String> para)
        throws Exception {
        String result = null;
        LOGGER.debug("---------------Start HttpClient Post---------------");
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        try {
            NameValuePair[] nameValuePairs = new NameValuePair[para.size()];
            int i = 0;
            for (String strNm : para.keySet()) {
                nameValuePairs[i++ ] = new NameValuePair(strNm, para.get(strNm));
            }

            postMethod.setRequestBody(nameValuePairs);
            int statusCode = httpClient.executeMethod(postMethod);

            if (statusCode != HttpStatus.SC_OK) {
                LOGGER.error("response status error" + statusCode);
                return result;
            }

            StringBuffer sb = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            result = sb.toString();
            LOGGER.debug("response result:" + result);
            if (br != null) {
                br.close();
            }
        } finally {
            postMethod.releaseConnection();
        }
        LOGGER.debug("---------------End HttpClient Post---------------");
        return result;
    }

    /**
     * 判断请求是否为手机.
     */
    public static boolean isMoblie(HttpServletRequest request) {
        boolean isMoblie = false;
        if (request.getHeader("User-Agent") != null) {
            for (String mobileAgent : MOBILE_AGENTS) {
                if (request.getHeader("User-Agent").toLowerCase().indexOf(mobileAgent) >= 0) {
                    isMoblie = true;
                    LOGGER.debug("request mobile is : {}", mobileAgent);
                    break;
                }
            }
        }
        return isMoblie;
    }

    /**
     * 如果是手机返回mobile ， 如果不是返回空.
     */
    public static String checkGetMobileSubFix(HttpServletRequest request) {
        if (isMoblie(request)) {
            return "mobile";
        }
        return "";
    }

    /**
     * 判断浏览器是否为微信.
     * @param request 请求request
     * @return True为是
     */
    public static boolean isWx(HttpServletRequest request) {
        String ua = ((HttpServletRequest) request).getHeader("user-agent").toLowerCase();
        LOGGER.debug("user-agent is :{}", ua);
        // if (ua.indexOf("micromessenger") > 0) {// 是微信浏览器
        if (ua.indexOf("chrome") > 0 || ua.indexOf("firefox") > 0 || ua.indexOf("mobile") > 0) {// 是微信浏览器
            return true;
        }
        return false;
    }

    /**
     * 写cookie
     * @param response
     * @param key
     * @param value
     * @param second 设置cookie存活期 例如10*60
     * @param path 设置cookie路径
     * @param domain 设置domain huilet 2013-3-19
     * @throws UnsupportedEncodingException
     */
    public static void saveCookie(HttpServletResponse response, String key, String value, int second, String path, String domain) {
        try {
            Cookie cookie = new Cookie(key, URLEncoder.encode(value, "UTF-8"));
            cookie.setPath(path);
            cookie.setMaxAge(second);
            if (!StringUtils.isEmpty(domain)) {
                cookie.setDomain(domain);
            }
            response.addCookie(cookie);
        } catch (Exception e) {
            LOGGER.error("saveCookie:", e);
        }
    }

    /**
     * 读cookie
     * @param request
     * @param key
     * @return huilet 2013-3-19
     * @throws UnsupportedEncodingException
     */
    public static String getCookie(HttpServletRequest request, String key) {
        Cookie cookies[] = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        for (int i = 0; i < cookies.length; i++ ) {
            if (cookies[i].getName().equals(key)) {
                try {
                    return URLDecoder.decode(cookies[i].getValue(), "UTF-8");
                } catch (Exception e) {
                    LOGGER.error("getCookie:", e);
                }

            }
        }
        return null;
    }

    /**
     * 删除cookie信息
     * @param request
     * @param response
     * @return
     */
    public static String exit(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) return "success";
        for (int i = 0; i < cookies.length; ++i) {
            Cookie cookie = cookies[i];
            cookie.setValue(null);
            cookie.setPath("/");
            cookie.setValue(null);
            cookie.setDomain("");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        return "success";
    }

    /**
     * 对文件名进行编码
     * @param filename
     * @param request
     * @return
     */
    public static String encodeFilename(String filename, HttpServletRequest request) {
        if (null == filename) return "";
        try {
            String extName = "";
            int i = filename.lastIndexOf(".");
            if (i != -1) {
                extName = filename.substring(i);
                filename = filename.substring(0, i);
            }

            // 文件名不能有\/:*?"<>|
            filename = filename.replace("\\", "");
            filename = filename.replace("/", "");
            filename = filename.replace(":", "");
            filename = filename.replace("*", "");
            filename = filename.replace("?", "");
            filename = filename.replace("\"", "");
            filename = filename.replace("<", "");
            filename = filename.replace(">", "");
            filename = filename.replace("|", "");
            filename = filename.replace("&", "");
            filename = filename.replace("#", "");
            filename = filename.replace("~", "");
            filename = filename.replace(";", "");
            filename = filename.replace("；", "");
            filename = filename.replace("。", "");
            filename = filename.replace(" ", "");
            filename = filename.replace(" ", "");

            String userAgent = request.getHeader("USER-AGENT");
            // 解决ie下载中文文件名乱码.
            boolean ie = StringUtils.containsIgnoreCase(userAgent, "msie");
            if (ie) {
                return URLEncoder.encode(filename) + extName;
            } else {
                return new String(filename.getBytes(), "ISO8859-1") + extName;
            }
        } catch (Exception e) {
            LOGGER.error("encodeFilename:", e);
            return filename;
        }
    }

    /**
     * 下载文件工具类
     * @param request
     * @param response
     * @param filename 浏览器端文件的名称
     * @param file 服务器端要下载的文件
     * @throws IOException
     */
    public static void download(HttpServletRequest request, HttpServletResponse response, String filename, File file)
        throws IOException {
        InputStream is = null;
        try {
            is = new FileInputStream(file);
            download(request, response, filename, is);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }

    /**
     * 文件下载工具类
     * @param request
     * @param response
     * @param filename 浏览器端文件的名称
     * @param is 服务器端要下载的文件流
     * @throws IOException
     */
    public static void download(HttpServletRequest request, HttpServletResponse response, String filename, InputStream is)
        throws IOException {
        setResponseHeader(request, response, filename);

        OutputStream out = null;
        try {
            out = response.getOutputStream();
            if (is != null && out != null) {
                IOUtils.copy(is, out);
            }
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 文件下载工具类
     * @param request
     * @param response
     * @param filename 浏览器端文件的方名称
     * @param datas 服务器端要下载的文件的数据
     * @throws IOException
     */
    public static void download(HttpServletRequest request, HttpServletResponse response, String filename, byte[] datas)
        throws IOException {
        setResponseHeader(request, response, filename);
        response.addHeader(CONTENT_LENGTH, String.valueOf(datas.length));
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(datas, 0, datas.length);
            out.flush();
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    /***
     * @param request
     * @param response
     * @param filename 浏览器端下载文件名称
     * @param is 服务器端要下载文件流
     * @throws IOException
     */
    public static void downloadInline(HttpServletRequest request, HttpServletResponse response, String filename, InputStream is)
        throws IOException {
        setResponseHeaderInline(request, response, filename);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            if (is != null && out != null) {
                IOUtils.copy(is, out);
            }
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 下载文件工具类
     * @param request
     * @param response
     * @param filename 浏览器端文件的名称
     * @param datas 服务器端文件的数据
     * @throws IOException
     */
    public static void downloadInline(HttpServletRequest request, HttpServletResponse response, String filename, byte[] datas)
        throws IOException {
        setResponseHeaderInline(request, response, filename);
        response.addHeader(CONTENT_LENGTH, String.valueOf(datas.length));
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(datas, 0, datas.length);
            out.flush();
        } catch (Throwable ex) {
            throw new RuntimeException(ex);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

    /**
     * 设置文件下载的请求头
     * @param request
     * @param response
     * @param filename
     */
    private static void setResponseHeader(HttpServletRequest request, HttpServletResponse response, String filename) {
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Cache-Control", "public");
        response.setHeader("Content-Description", "File Transfer");
        String downfileName = encodeFilename(filename, request);
        response.setContentType(DOWNLOAD_MIME);
        response.setHeader(DISPOSITION, ATTACH_FILE + "\"" + downfileName + "\"");
    }

    private static void setResponseHeaderInline(HttpServletRequest request, HttpServletResponse response, String filename) {
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Cache-Control", "public");
        response.setHeader("Content-Description", "File Transfer");
        String downfileName = encodeFilename(filename, request);
        response.setContentType(DOWNLOAD_MIME);
        response.setHeader(DISPOSITION, INLINE_FILE + "\"" + downfileName + "\"");
    }
}
